﻿using System;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using SLS.Base;
using SLS.DataBase;
using SLS.ExClassLib.Data;
using SLS.ExClassLib.Database;
using SLS.ExClassLib.Event;
using SLS.ExClassLib.Events;
using SLS.ExClassLib.Message;
using SLS.ExClassLib.RTIService;
namespace SLS.Presentation
{
    /// <summary>
    /// Interaction logic forRelationKey.xaml
    /// Based On the entry datarow, generate the key structure and return the result key
    /// Now load GTPREDef dynamically
    /// Generate GoodsMasterKeyRelations dynamically
    /// </summary>
    public partial class RelationKeyService : SLBC
    {

        string MGDKEYTable;
        string SGDKEYTable;
        string MGDKEY = "", SGDKEY = "";
        public string MasterCallerPath = "";
        public RelationKeyService()
        {
            InitializeComponent();
            this.BaseTable = "GoodsMasterKeyRelation";
            this.Address = "ManageRelationKey";
        } 
        #region =================Property=================
        public SLDBSET setThis
        {
            get
            {
                return (SLDBSET)DataContext;
            }
        }
        private DataRow m_dwGDKEY;
        public DataRow dwGDKEY
        {
            get
            {
                return m_dwGDKEY;
            }
            set
            {
                m_dwGDKEY = value;
                if (m_dwGDKEY != null)
                {
                    SetUpKeyRelation(m_dwGDKEY);
                }
            }
        }
        private DataRow m_dwGoodsMasterKeyRelation;
        public DataRow dwGoodsMasterKeyRelation
        {
            get
            {
                return m_dwGoodsMasterKeyRelation;
            }
            set
            {
                m_dwGoodsMasterKeyRelation = value;
                bool raiseGoodsMasterKeyRelationComplete = false;
                if (m_dwGoodsMasterKeyRelation != null)
                {
                    SetUpComboBox(m_dwGoodsMasterKeyRelation);
                    string SUBSTATUS = m_dwGDKEY["SUBSTATUS"].ToString().Trim();
                    if (!SUBSTATUS.Contains("GoodsMasterKeyRelationComplete;")
                        && sGDKEYComboBox.IsEnabled == false
                        && mGDKEYComboBox.IsEnabled == false
                        )
                    {
                        raiseGoodsMasterKeyRelationComplete = true;
                    }
                    string CreationSource = m_dwGDKEY["CreationSource"].ToString().Trim();
                    if (CreationSource == "AUTO")
                    {
                        raiseGoodsMasterKeyRelationComplete = true;
                    }
                    if (raiseGoodsMasterKeyRelationComplete)
                    {
                        m_dwGDKEY["SUBSTATUS"] = SUBSTATUS + "GoodsMasterKeyRelationComplete;";
                        MessageEx msg = new MessageEx(MasterCallerPath, "UIFederation", "OnKeyRelaitonComplete", "YES");
                        msg.TimeStamp = ContactRTIService.Instance.GetRTITimeStamp(msg);
                        //EventDispatcher.Instance.POSTUI2UIMessage(msg, m_dwGDKEY);
                        EventDispatcher.Instance.Publish(msg, m_dwGDKEY);
                    }
                    sGDKEYComboBox.LostFocus += new RoutedEventHandler(mGDKEYComboBox_LostFocus);
                    mGDKEYComboBox.LostFocus += new RoutedEventHandler(mGDKEYComboBox_LostFocus);
                }
            }
        }
        public DataTable TBGoodsMasterKeyRelation
        {
            get
            {
                return ((SLDBSET)DataContext).Tables["GoodsMasterKeyRelation"];
            }
        }
        public string CombinationKey
        {
            get
            {
                return m_dwGDKEY["GDKEY"].ToString();
            }
            set
            {
                m_dwGoodsMasterKeyRelation["GDKEY"] = value;
                m_dwGDKEY["GDKEY"] = value;
                string SUBSTATUS = m_dwGDKEY["SUBSTATUS"].ToString().Trim();
                if (!SUBSTATUS.Contains("GoodsMasterKeyRelationComplete;"))
                {
                    m_dwGDKEY["SUBSTATUS"] = SUBSTATUS + "GoodsMasterKeyRelationComplete;";
                }
            }
        }

        #endregion

        #region =================SetUpKeyRelation=================
        public override void SetUpKeyRelation(DataRow dwGDKEY)
        {
            try
            {
                if (dwGDKEY == null)
                    return;
                string SM = dwGDKEY["SM"].ToString().Trim();
                string KREAL = dwGDKEY.Table.TableName;
                string KEYDEFTYPE = dwGDKEY["KEYDEFTYPE"].ToString().Trim();
                string GTPRE = dwGDKEY["GTPRE"].ToString().Trim();
                string GTKEY = dwGDKEY["GTKEY"].ToString().Trim();
                string GDKEY = dwGDKEY["GDKEY"].ToString().Trim();
                if (KREAL == "GoodsMasterProperty"
                    || KREAL == "GoodsMasterAssemblePoint"
                    || KREAL == "GoodsTypeAssemblePointDef"
                    || KREAL == "GoodsTypePropertyDef"
                    )
                {
                    return;
                }
                string expression;
                expression = "SM='" + SM
                + "' AND KREAL='" + KREAL
                + "' AND KEYDEFTYPE='" + KEYDEFTYPE
                + "' AND GTPRE='" + GTPRE
                + "' AND GTKEY='" + GTKEY
                + "' AND GDKEY='" + GDKEY + "'";
                DataRow[] dwTemps = TBGoodsMasterKeyRelation.Select(expression);
                if (dwTemps.Count() == 0)
                {
                    DataSet setResult = GenerateGoodsMasterKeyRelation(dwGDKEY);
                    TBGoodsMasterKeyRelation.Merge(setResult.Tables[0]);
                }
                dwTemps = TBGoodsMasterKeyRelation.Select(expression);
                if (dwTemps.Count() > 0)
                {
                    dwGoodsMasterKeyRelation = dwTemps[0];
                }

            }
            catch (Exception ex)
            {
                Tracer.Error("RelationKey " + this.Name + ".FillInCombo ", ex);
            }
        }
        public DataSet GenerateGoodsMasterKeyRelation(DataRow dwGDKEY)
        {
            DataSet setReturn = new DataSet();
            try
            {
                string SUBSTATUS = dwGDKEY["SUBSTATUS"].ToString().Trim();
                DataSet setRequest = new DataSet();
                MessageEx msg = new MessageEx();
                DataRow dwQueryCond = null;
                dwQueryCond = DataAccessService.Instance.setQueryCond.GoodsMasterKeyRelationQueryCond.NewRow();
                dwQueryCond["QUERYTYPE"] = "CreateByQuery";
                dwQueryCond["CONDTYPE"] = "IX_GoodsMasterKeyRelation_Key";
                dwQueryCond["SM"] = dwGDKEY["SM"];
                dwQueryCond["KREAL"] = dwGDKEY.Table.TableName;
                dwQueryCond["KEYDEFTYPE"] = dwGDKEY["KEYDEFTYPE"];
                dwQueryCond["GTPRE"] = dwGDKEY["GTPRE"];
                dwQueryCond["GTKEY"] = dwGDKEY["GTKEY"];
                dwQueryCond["GDKEY"] = dwGDKEY["GDKEY"];
                dwQueryCond["LINE"] = 0;
                setRequest = (DataSet)DataAccessService.Instance.ImportDataTable(setRequest, dwQueryCond);
                setRequest.DataSetName = "GoodsMasterKeyRelationQueryCond";
                DataSet set4Ref = new DataSet();
                set4Ref = (DataSet)DataAccessService.Instance.ImportDataTable(set4Ref, dwGDKEY);
                ExDataRow row = new ExDataRow();
                setReturn = row.QueryAndCreateData(setRequest, dwQueryCond, set4Ref);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        private void FillInCombo(ComboBox sender, string TBName, string smGDKEY)
        {
            try
            {
                DataSet setTemp = new DataSet();
                setTemp = (DataSet)DataAccessService.Instance.GetDataBySM(TBName);
                sender.ItemsSource = setTemp.Tables[TBName].AsDataView();
                string MemberPath = "GDKEY";
                if (TBName == "SysKeyData")
                    MemberPath = "CurrentValue";
                if (TBName == "KeyBoardInput")
                    MemberPath = "KeyBoardText";
                sender.DisplayMemberPath = MemberPath;
                sender.SelectedValuePath = MemberPath;
                sender.IsEditable = true;
                sender.IsEnabled = true;
                sender.Text = smGDKEY;
                sender.LostFocus += new RoutedEventHandler(mGDKEYComboBox_LostFocus);
            }
            catch (Exception ex)
            {
                Tracer.Error("RelationKey " + this.Name + ".FillInCombo ", ex);
            }
        }
        private void UpdateCombinationKey()
        {
            try
            {
                if (MGDKEYTable != SGDKEYTable
                    && mGDKEYComboBox.Text.Trim() != "")
                {
                    if ((sGDKEYComboBox.Visibility != System.Windows.Visibility.Hidden
                        && sGDKEYComboBox.Text != "")
                        || sGDKEYComboBox.Visibility == System.Windows.Visibility.Hidden)
                    {

                    }
                }
                if (MGDKEYTable == "KeyBoardInput"
                    && mGDKEYComboBox.Text.Trim() == "")
                    return;

                if (MGDKEYTable != "KeyBoardInput"
                    && mGDKEYComboBox.Text.Trim() != ""
                    && sGDKEYComboBox.Text == ""
                    )
                    return;
                if (sGDKEYComboBox.Text == "")
                {
                    CombinationKey = mGDKEYComboBox.Text;
                }
                else
                {
                    string Line0 = m_dwGoodsMasterKeyRelation["Line"].ToString().Trim();
                    if (Line0 == "0")
                    {
                        CombinationKey = mGDKEYComboBox.Text
                            + "." + sGDKEYComboBox.Text
                            ;
                    }
                    else
                    {
                        CombinationKey = mGDKEYComboBox.Text
                            + "." + sGDKEYComboBox.Text
                            + "." + Line0;
                    }
                }
                this.mGDKEYComboBox.IsEnabled = false;
                this.sGDKEYComboBox.IsEnabled = false;
                DataSet setEvent = new DataSet();
                MessageEx msg = new MessageEx();
                msg.JobID = "OnSaveRecord";
                setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, m_dwGDKEY);
                setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, m_dwGoodsMasterKeyRelation);
                msg.setEvent = setEvent;
                DataAccessService.Instance.QueryData(msg);
            }
            catch (Exception ex)
            {
                Tracer.Error("RelationKey " + this.Name + ".FillInCombo ", ex);
            }
        }
        private void SetUpComboBox(DataRow dwKeyRelation)
        {
            try
            {
                MGDKEYTable = dwKeyRelation["MKREAL"].ToString();
                SGDKEYTable = dwKeyRelation["SKREAL"].ToString();
                MGDKEY = dwKeyRelation["MGDKEY"].ToString();
                SGDKEY = dwKeyRelation["SGDKEY"].ToString();
                #region CreateCombox
                FillInCombo(mGDKEYComboBox, MGDKEYTable, MGDKEY);
                FillInCombo(sGDKEYComboBox, SGDKEYTable, SGDKEY);
                mGDKEYComboBox.IsEnabled = true;
                sGDKEYComboBox.LostFocus -= new RoutedEventHandler(mGDKEYComboBox_LostFocus);
                mGDKEYComboBox.LostFocus -= new RoutedEventHandler(mGDKEYComboBox_LostFocus);
                #endregion
                //1> Only one is possible
                if (MGDKEYTable == "KeyBoardInput")
                {
                    mGDKEYComboBox.Text = MGDKEY;
                    if (MGDKEY.Trim() != "")
                    {
                        mGDKEYComboBox.IsEnabled = false;
                    }
                    sGDKEYComboBox.IsEnabled = false;
                    sGDKEYComboBox.Text = "";
                    sGDKEYComboBox.Visibility = System.Windows.Visibility.Hidden;
                    return;
                }
                //2> if MGDKEYTable=Table1 and SGDKEYTable=SysKeyData
                //4>如果MGDKEY是空值，一个从另外的表选择，另外一个是流水号
                //  如果MGDKEY有值，一个从另外的表选择，另外一个是流水号
                string SGDKEYEnabled = dwKeyRelation["SGDKEYENABLED"].ToString().Trim();

                if (SGDKEYTable == "SysKeyData")
                {
                    if (SGDKEYEnabled == "YES")
                    {
                        #region  SGDKEY IsEnabled=TRUE
                        sGDKEYComboBox.IsEnabled = true;
                        sGDKEYComboBox.Text = SGDKEY;

                        #endregion

                        #region MGDKEY IsEnabled=TRUE/False

                        mGDKEYComboBox.Text = MGDKEY;
                        if (MGDKEY != "")
                        {
                            if (SGDKEY == "")
                            {
                                mGDKEYComboBox_LostFocus(mGDKEYComboBox, null);
                            }
                            else
                            {
                                sGDKEYComboBox.IsEnabled = false;
                            }
                            mGDKEYComboBox.IsEnabled = false;
                        }
                        else
                        {
                            mGDKEYComboBox.IsEnabled = true;
                        }
                        #endregion
                    }
                    else
                    {
                        sGDKEYComboBox.IsEnabled = false;
                        mGDKEYComboBox.IsEnabled = false;
                        mGDKEYComboBox.Text = MGDKEY;
                    }
                    return;
                }
                //3> MGDKEYTable=Table1	SGDKEYTable=Table2 
                #region SGDKEY is Keyboard input while MGDKEY not. or SGDKEY is to choose from other table.
                #region  SGDKEY IsEnabled=TRUE
                sGDKEYComboBox.IsEnabled = true;
                sGDKEYComboBox.Text = SGDKEY;
                #endregion

                #region MGDKEY IsEnabled=TRUE
                mGDKEYComboBox.IsEnabled = true;
                mGDKEYComboBox.Text = MGDKEY;
                #endregion
                #endregion
                return;

            }
            catch (Exception ex)
            {
                Tracer.Error("RelationKey " + this.Name + ".SetUpComboBox ", ex);
            }
        }
        #endregion
        private void mGDKEYComboBox_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                //1>Get Condtion MKREAL	MKeyDefType	MGTPRE	MGTKEY
                //2>Fileter SGDKEY
                //3>Send to SysKeyData, get the maxid
                #region 1>Get KeyCondtion
                string KeyCondition = "";
                string SM = m_dwGoodsMasterKeyRelation["SM"].ToString().Trim();
                string MKREAL = m_dwGoodsMasterKeyRelation["MKREAL"].ToString().Trim();
                string MKeyDefType = m_dwGoodsMasterKeyRelation["MKEYDEFTYPE"].ToString().Trim();
                string MGTPRE = m_dwGoodsMasterKeyRelation["MGTPRE"].ToString().Trim();
                string MGTKEY = m_dwGoodsMasterKeyRelation["MGTKEY"].ToString().Trim();
                string SKREAL = m_dwGoodsMasterKeyRelation["SKREAL"].ToString().Trim();
                if (MGDKEY != mGDKEYComboBox.Text)
                {
                    MGDKEY = mGDKEYComboBox.Text;
                }
                if (SKREAL == "KeyBoardInput")
                {
                    if (SGDKEY != sGDKEYComboBox.Text)
                    {
                        SGDKEY = sGDKEYComboBox.Text;
                    }
                }
                if (MGDKEY == "")
                    return;
                KeyCondition = MKREAL + "." + SM + "." + MKeyDefType + "." + MGTPRE + "." + MGTKEY + "." + MGDKEY;
                #endregion
                #region  2>Send to SysKeyData, get the maxid
                if (SKREAL == "SysKeyData")
                {
                    if (SGDKEY != "")
                        return;
                    ExDataRow row = new ExDataRow();
                    int newValue = row.GetMaxIDSysKeyData(MKREAL, KeyCondition);
                    #region Set   SGDKEY
                    SGDKEY = newValue.ToString();
                    #endregion
                }
                #endregion

                #region Update the MGDKEY/SGDKEY;
                this.mGDKEYComboBox.IsEnabled = true;
                this.sGDKEYComboBox.IsEnabled = true;
                m_dwGoodsMasterKeyRelation["MGDKEY"] = MGDKEY;
                mGDKEYComboBox.Text = MGDKEY;
                m_dwGoodsMasterKeyRelation["SGDKEY"] = SGDKEY;
                sGDKEYComboBox.Text = SGDKEY;
                UpdateCombinationKey();
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error("RelationKey " + this.Name + ".SetUpComboBox ", ex);
            }
        }
    }
}